package com.hjwoo.app.utils;

import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.view.KeyEvent;
import android.widget.Toast;

import com.hjwoo.app.R;
import com.umeng.analytics.MobclickAgent;

/***
 * 双击退出
 * @author FireAnt（http://my.oschina.net/LittleDY）
 * @created 2015年1月5日 下午7:07:44
 */
public class DoubleClickExitHelper
{

    private final Activity mActivity;

    private boolean isOnKeyBacking;
    private Handler mHandler;
    private Toast   mBackToast;
    private Runnable onBackTimeRunnable = new Runnable()
    {

        @Override
        public void run()
        {
            isOnKeyBacking = false;
            if (mBackToast != null)
            {
                mBackToast.cancel();
            }
        }
    };

    public DoubleClickExitHelper(Activity activity)
    {
        mActivity = activity;
        mHandler = new Handler(Looper.getMainLooper());
    }

    /**
     * Activity onKeyDown事件
     */
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode != KeyEvent.KEYCODE_BACK)
        {
            return false;
        }
        if (isOnKeyBacking)
        {
            mHandler.removeCallbacks(onBackTimeRunnable);
            if (mBackToast != null)
            {
                mBackToast.cancel();
            }
            // 退出
            //   友盟统计：     如果开发者调用Process.kill或者System.exit之类的方法杀死进程，请务必在此之前调用MobclickAgent.onKillProcess(Context context)方法，用来保存统计数据。
            MobclickAgent.onKillProcess(mActivity);
            mActivity.finish();
            return true;
        }
        else
        {
            isOnKeyBacking = true;
            if (mBackToast == null)
            {
                mBackToast = Toast.makeText(mActivity, R.string.tip_double_click_exit, Toast.LENGTH_SHORT);
            }
            mBackToast.show();
//			等待两秒
            mHandler.postDelayed(onBackTimeRunnable, 2000);
            return true;
        }
    }
}
